package com.tanhua.sso.controller;

import com.tanhua.sso.pojo.User;
import com.tanhua.sso.service.loginService;
import com.tanhua.sso.vo.ErrorResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("user")
@RestController
public class UserController {

    @Autowired
    private loginService service;
    @PostMapping("loginVerification")
    public ResponseEntity<Object> loginUser(@RequestBody Map<String,String>param){
        try {
            String phone = param.get("phone");
            String code = param.get("verificationCode");
            String data = service.login(phone, code);
            if (StringUtils.isNotEmpty(data)){
                //登录成功
                Map<String,Object>map=new HashMap<>();
//                String[] split1 = data.split(",");
                String[] split1 = StringUtils.split(data, ",");
                for (String s : split1) {

                    System.out.println(s);
                }
                map.put("token",split1[0]);
                map.put("isNew",Boolean.valueOf(split1[1]));
                ErrorResult result = ErrorResult.builder().errCode("000000").errMessage("登录成功").build();
                return ResponseEntity.ok(map);
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        ErrorResult result = ErrorResult.builder().errCode("000002").errMessage("登录失败").build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
    }

    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token") String token) {
        return this.service.queryUserByToken(token);
    }
}
